const PATH = 'assets/resources/datas/'; //存放数据路径
export class EditorFile {
    /**
    * 保存数据
    * @param dataSavePath 数据存储文件命名+格式  例:data.json
    * @param data 数据
    * @param cb 回调
    */
    public static saveDataToPath (dataSavePath: String, data: any, cb?: any) {
        //@ts-ignore
        const projectPath = window.cce.project as string; //当前项目文件路径
        projectPath.replace("\\", " / ");
        const filePath = `${projectPath}/` + PATH;
        //@ts-ignore
        const fs = require('fs');
        const write = () => {
            fs.writeFile(filePath + dataSavePath, data, (err: Error) => {
                if (err) {
                    console.error("error", err);
                } else {
                    console.warn('success');
                }
                cb && cb()
            });
        }

        fs.exists(filePath, function (e: boolean) {
            if (!e) {
                fs.mkdir(filePath, function (err: Error) {
                    if (err) {
                        console.error("error", err);
                    } else {
                        console.warn('success');
                        write();
                    }
                });
            } else {
                write();
            }
        });
    }

    /**
     * 加载数据
     * @param dataSavePath 数据存储文件命名+格式  例:data.json
     * @param successCb 成功回调
     * @param failCb 失败回调
     */
    public static loadDataToPath (dataSavePath: String, successCb: Function, failCb?: Function) {
        //@ts-ignore
        const projectPath = window.cce.project as string;
        projectPath.replace("\\", " / ");
        let path = `${projectPath}/` + PATH + dataSavePath;
        //@ts-ignore
        const fs = require('fs');

        fs.readFile(path, 'utf-8', (err: Error, data: any) => {
            if (err) {
                failCb && failCb();
                return console.error('error:' + err);
            }
            successCb(JSON.parse(data));
        })
    }
}